package com.css.zfzx.sjcj.modules.qhsoildynamic.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.modules.qhsoildynamic.repository.QhSoilDynamicNativeRepository;
import com.css.zfzx.sjcj.modules.qhsoildynamic.repository.QhSoilDynamicRepository;
import com.css.zfzx.sjcj.modules.qhsoildynamic.repository.entity.QhSoilDynamicEntity;
import com.css.zfzx.sjcj.modules.qhsoildynamic.service.QhSoilDynamicService;
import com.css.zfzx.sjcj.modules.qhsoildynamic.viewobjects.QhSoilDynamicQueryParams;
import com.css.zfzx.sjcj.modules.qhsoildynamic.viewobjects.QhSoilDynamicVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author aa
 * @date 2020-11-13
 */
@Slf4j
@Service
public class QhSoilDynamicServiceImpl implements QhSoilDynamicService {

	@Autowired
    private QhSoilDynamicRepository qhSoilDynamicRepository;
    @Autowired
    private QhSoilDynamicNativeRepository qhSoilDynamicNativeRepository;

    @Override
    public JSONObject queryQhSoilDynamics(QhSoilDynamicQueryParams queryParams, int curPage, int pageSize) {
        Page<QhSoilDynamicEntity> qhSoilDynamicPage = this.qhSoilDynamicNativeRepository.queryQhSoilDynamics(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(qhSoilDynamicPage);
        return jsonObject;
    }


    @Override
    public QhSoilDynamicEntity getQhSoilDynamic(String id) {
        QhSoilDynamicEntity qhSoilDynamic = this.qhSoilDynamicRepository.findById(id).orElse(null);
         return qhSoilDynamic;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhSoilDynamicEntity saveQhSoilDynamic(QhSoilDynamicEntity qhSoilDynamic) {
        String uuid = UUIDGenerator.getUUID();
        qhSoilDynamic.setId(uuid);
        qhSoilDynamic.setCreateUser(PlatformSessionUtils.getUserId());
        qhSoilDynamic.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        qhSoilDynamic.setIsValid("1");
        qhSoilDynamic.setReviewStatus("0");
        qhSoilDynamic.setQualityinspectionStatus("0");
        this.qhSoilDynamicRepository.save(qhSoilDynamic);
        return qhSoilDynamic;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhSoilDynamicEntity updateQhSoilDynamic(QhSoilDynamicEntity qhSoilDynamic) {
        qhSoilDynamic.setUpdateUser(PlatformSessionUtils.getUserId());
        qhSoilDynamic.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.qhSoilDynamicRepository.save(qhSoilDynamic);
        return qhSoilDynamic;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteQhSoilDynamics(List<String> ids) {
        List<QhSoilDynamicEntity> qhSoilDynamicList = this.qhSoilDynamicRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(qhSoilDynamicList) && qhSoilDynamicList.size() > 0) {
            for(QhSoilDynamicEntity qhSoilDynamic : qhSoilDynamicList) {
                this.qhSoilDynamicRepository.delete(qhSoilDynamic);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitQhSoilDynamics(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhSoilDynamicEntity> qhDrillOverviewList = this.qhSoilDynamicRepository.findAllById(idList);
        if(!PlatformObjectUtils.isEmpty(qhDrillOverviewList) && qhDrillOverviewList.size() > 0) {
            for(QhSoilDynamicEntity qhDrillOverview : qhDrillOverviewList) {
                qhDrillOverview.setUpdateUser(PlatformSessionUtils.getUserId());
                qhDrillOverview.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                qhDrillOverview.setReviewStatus("1");
                this.qhSoilDynamicRepository.save(qhDrillOverview);
            }
        }
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            params.setTitleRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<QhSoilDynamicVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), QhSoilDynamicVO.class, params);
            List<QhSoilDynamicVO> list = result.getList();
            // 批量新增
            this.saveExcel(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<QhSoilDynamicVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    QhSoilDynamicVO areaVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + areaVO.getRowNum() + "行" + areaVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }

    @Override
    public String exportExcel(String ids, HttpServletResponse response) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhSoilDynamicEntity> areaEntities = qhSoilDynamicRepository.findAllById(idList);

        return exportExcel(areaEntities,response);
    }

    @Override
    public String exportExcel(List<QhSoilDynamicEntity> areaEntities, HttpServletResponse response) {
        try {
            // 深拷贝
            ArrayList<QhSoilDynamicVO> vos = new ArrayList<>();
            for (QhSoilDynamicEntity areaEntity : areaEntities) {
                QhSoilDynamicVO vo = new QhSoilDynamicVO();
                BeanUtils.copyProperties(areaEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "土动力测试数据统计", "土动力测试数据", QhSoilDynamicVO.class, "土动力测试数据.xls", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    private void saveExcel(List<QhSoilDynamicVO> list) {
        for (int i = 0; i < list.size(); i++) {
            QhSoilDynamicEntity areaEntity = new QhSoilDynamicEntity();
            QhSoilDynamicVO areaVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(areaVO, areaEntity);
            saveQhSoilDynamic(areaEntity);
        }
    }
}
